import sys
from os import system
from pathlib import Path
from typing import List

system('cls')

# 改变路径
current_folder = Path(__file__).absolute().parent
father_folder = str(current_folder.parent)
sys.path.append(father_folder)

from utils.JSON的输入和输出 import 写入json, 读取json  # noqa
from utils.文件夹下的所有文件 import getFilesList  # noqa

src_dir = 'output/IDS_To_JSON'
json_names = getFilesList(src_dir)


def canEllipsis(prev: int or str, cur: int, fol: int) -> int:
    if prev == '~' and fol - cur == 6:
        return 0  # 省略
    if prev != '~' and cur - prev == 6 and fol - cur == 6:
        return 1  # 变成 ~
    return 2  # 不可省略


def ellipsisLines(lines: List[int]) -> str:
    tmp = []
    for i in range(len(lines)):
        if i > 0 and i < len(lines) - 1:
            if canEllipsis(tmp[-1], lines[i], lines[i+1]) == 1:
                tmp.append('~')
            elif canEllipsis(tmp[-1], lines[i], lines[i+1]) == 2:
                tmp.append(lines[i])
        else:
            tmp.append(lines[i])
    res = ''
    for i, c in enumerate(tmp):
        res += f'{c}'
        if (i < len(tmp) - 1 and tmp[i] != '~' and tmp[i+1] != '~'):
            res += ', '
    return f'[{res}]'

def shouldEliminate(source: str) -> bool:
    if source in ['coming soon', 'Temp', "-"]:
        return True 
    if source.startswith('_') or source.startswith('reserve0'):
        return True
    if source == 'mission ': return True
    return False

print('JSON_not_translated:line_1st\t\t\t<amount> [position]', '\n'+'-'*70)

for name in json_names:
    line_nums: list[int] = []
    path = f'{src_dir}/{name}'
    json_list = 读取json(path)
    for index, item in enumerate(json_list):
        if shouldEliminate(item['source']):
            item['trans'] = item['source']
        if not item["trans"] and not item['COMMAND'] in ['_GRP_', '_LNG_']:
            line_nums.append(index * 6 + 2)
    if line_nums:
        print(f'./output/IDS_To_JSON/{name}:{line_nums[0]+4}\t', f'<{len(line_nums)}>', ellipsisLines(line_nums))
    写入json(json_list, path)